package com.isay.frameworklib.okhttp;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by cywu4 on 2018/12/17.
 */
public class HttpCallBack implements okhttp3.Callback {
    private int ret;
    private String msg;
    private String content;

    private static final Handler sHandler = new Handler(Looper.getMainLooper());

    private ICommonCallback mCallback;

    public HttpCallBack(ICommonCallback callback) {
        mCallback = callback;
    }


    @Override
    public void onResponse(Call call, final Response response) {
        boolean isSuccess = false;
        try {
            JSONObject jsonObject = new JSONObject(response.body().string());
            ret = jsonObject.optInt("ret");
            msg = jsonObject.optString("msg");
            content = jsonObject.optString("content");
            isSuccess = true;
        } catch (final Exception e) {
            isSuccess = false;
            sHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mCallback != null) {
                        mCallback.onFailure(e);
                    }
                }
            });
        }
        //回调结果
        if (isSuccess) {
            sHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mCallback != null) {
                        mCallback.onSuccess(ret, msg, content);
                    }
                }
            });
        }
    }

    @Override
    public void onFailure(Call call, final IOException e) {
        if (mCallback != null) {
            sHandler.post(new Runnable() {
                @Override
                public void run() {
                    mCallback.onFailure(e);
                }
            });
        }
    }


}
